package com.hmall.getaway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.getaway.config.AuthProperties;
import com.hmall.getaway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered{

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        // 排除不需要验证的路径
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        //获取请求头中的token
        String token = null;
        List<String> authorization = request.getHeaders().get("Authorization");
        if(!CollUtils.isEmpty(authorization)){
            token = authorization.get(0);
        }
        // 校验token并解析  校验失败则返回401状态码
        Long userId= null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 设置userId到请求头中
        exchange.getRequest().mutate().header("userId",userId.toString()).build();
        // 放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String pathstring) {
        for (String path:authProperties.getExcludePaths()){
            if (antPathMatcher.match(path,pathstring)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
